import React, { useState } from 'react';

// 这个组件处理用户点击下单按钮的逻辑
export function OrderPage (){
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const apiHostUrl = process.env.API_HOST_URL ? process.env.API_HOST_URL : "https://117.72.71.221:8091";

    // 获取cookie的函数
    const getCookie = (name: string) => {
        const cookieArr = document.cookie.split(';');
        for (let i = 0; i < cookieArr.length; i++) {
            const cookiePair = cookieArr[i].split('=');
            if (name === cookiePair[0].trim()) {
                return decodeURIComponent(cookiePair[1]);
            }
        }
        return null;
    };

    // 处理下单点击事件
    const handleOrder = async () => {
        setLoading(true);
        setError(null);

        const userId = getCookie('loginToken');
        if (!userId) {
            window.location.href = 'login.html'; // 跳转到登录页
            return;
        }

        const productId = '100010090091';
        const url = `${apiHostUrl}/api/v1/alipay/create_pay_order`;

        const requestBody = {
            userId,
            productId,
        };

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestBody),
            });

            const json = await response.json();
            if (json.code === '0000') { // 假设成功的code是"0000"
                const formHtml = json.data; // 获取data字段中的HTML表单字符串
                const formElement = document.createElement('div');
                formElement.innerHTML = formHtml;
                document.body.appendChild(formElement);
                document.forms[0].submit(); // 自动提交表单
            } else {
                setError(json.info); // 输出错误信息
            }
        } catch (error) {
            console.error('Error:', error);
            // @ts-ignore
            setError('请求失败，请重试。');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="container" style={{ maxWidth: '600px', margin: '50px auto', padding: '20px', backgroundColor: '#fff', boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)' }}>
            <div className="product-info" style={{ marginBottom: '20px', border: '1px solid #ddd', padding: '10px', textAlign: 'center' }}>
                <h2>美女程序员 - 同款机械键盘</h2>
                <img width="350" src="images/sku-keyboard-001.png" alt="机械键盘"/>
                <p style={{ fontSize: '36px', fontWeight: 'bold', color: 'red', margin: '20px 0 0' }}>价格：¥1.68</p>
            </div>
            <button
                id="orderButton"
                className="order-button"
                style={{ display: 'block', width: 'calc(100% - 40px)', padding: '10px', margin: '10px auto', fontSize: '16px', color: '#fff', backgroundColor: '#007bff', border: 'none', cursor: 'pointer', borderRadius: '20px' }}
                onClick={handleOrder}
                disabled={loading}
            >
                {loading ? '处理中...' : '立即下单「沙箱支付」'}
            </button>
            {error && <p style={{ color: 'red' }}>{error}</p>}
            <span className="account-info" style={{ fontSize: '12px', textAlign: 'center', display: 'block', margin: '10px 0' }}>
        测试账号：kvhmoj3832@sandbox.com 密码：111111 支付：111111
      </span>
        </div>
    );
};

export default OrderPage;